package org.wedding.config.redis;

import cn.dev33.satoken.stp.StpUtil;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.transaction.annotation.Transactional;
import org.wedding.center.entity.CouponInfo;
import org.wedding.center.entity.NoticeInfo;
import org.wedding.center.service.CouponInfoService;
import org.wedding.center.service.NoticeInfoService;

import javax.annotation.Resource;

/**
 * redis监听器 按KEY监听
 */
public class CouponKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Resource
    private CouponInfoService couponInfoService;
    @Resource
    private NoticeInfoService noticeInfoService;

    // 构造函数，传入RedisMessageListenerContainer参数
    public CouponKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    // 重写onMessage方法，处理消息
    @Override
    @Transactional
    public void onMessage(Message message, byte[] pattern) {
        // 将消息转换为字符串
        String key = message.toString();
        // 输出优惠卷信息
        System.out.println("优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！优惠卷过期！");
        // 判断key是否以"coupon:"开头
        if (key.startsWith("coupon:")) {
            // 处理coupon相关的超时逻辑
//            System.out.println("优惠卷key: " + key);
            String id = key.replace("coupon:", "");
            System.out.println("优惠卷id: " + id);
            //更新优惠卷过期状态
            couponInfoService.expiredById(id);
            CouponInfo couponInfo = couponInfoService.view(id).getData();
            if (couponInfo != null) {
                //发送优惠卷过期通知
                noticeInfoService.add(NoticeInfo.builder()
                        .userId(couponInfo.getUserId())
                        .userName(couponInfo.getUserName())
                        .notice("您的优惠卷已过期,请前往个人中心查看！")
                        .type("3")
                        .quality("middle")
                        .creator(StpUtil.getLoginIdAsString())
                        .build());
            }
        }
    }
}
